<!--
 * @Descripttion: 目录管理
 * @version: 
 * @Author: 穆宏宇
 * @Date: 2020-11-23 13:56:38
 * @LastEditors: 穆宏宇
 * @LastEditTime: 2020-11-24 14:25:25
-->
<!-- 带图片上传 -->
<template>
	<div class="bigDiv">
		<el-form inline label-width="100">
			<div class="topNav">
				<el-button type="text" @click="openDialogEdit('root',{})">
					新建根节点
				</el-button>
				<el-button type="text" @click="getTree" style="float:right;">搜索</el-button>
			</div>
			<el-form-item label="有效">
				<el-select v-model="queryParams.isDel" clearable size="mini">
					<el-option value="" label="全部"></el-option>
					<el-option value="0" label="有效"></el-option>
					<el-option value="1" label="无效"></el-option>
				</el-select>
			</el-form-item>
		</el-form>
		<!-- <el-row type="flex" justify="end" class="mb10">
			<el-col :span="6">
				<el-button type="success" size="small" @click="openDialogEdit('root',{})">
					新建根节点
				</el-button>
			</el-col>
		</el-row> -->
		<el-table :data="tableData" ref="table" style="width: 100%" row-key="id" border lazy :load="load"
			:height="maxHeightNow" :tree-props="{children: 'children', hasChildren: 'haveChildren'}">
			<el-table-column minWidth="300px" prop="categoryName" label="商品目录" align="left">
			</el-table-column>
			<el-table-column width="100px" label="有效性">
				<template slot-scope="scope">
					<span :class="{ success: scope.row.isDel == '0' }">
						{{scope.row.isDel==='0'?'有效':'无效'}}
					</span>
				</template>
			</el-table-column>
			<el-table-column width="100px" label="电商编码" prop="dcCode">
			</el-table-column>
			<!-- <el-table-column width="130px" label="类型">
				<template slot-scope="scope">
					{{ categoryType[scope.row.itemType].text || "" }}
				</template>
			</el-table-column> -->
			<el-table-column width="130px" label="商品类型">
				<template slot-scope="scope">
					<span v-for="item in itemTypeList">
						<template v-if="item.value == scope.row.itemType">
							{{ item.label }}
						</template>
					</span>
				</template>
			</el-table-column>
			<el-table-column width="170px" label="分类图片">
				<template slot-scope="scope">
					<img :src="scope.row.imgUrl" width="50px" v-if="scope.row.imgUrl" />
				</template>
			</el-table-column>
			<el-table-column label="操作" width="470">
				<template slot-scope="scope">
					<el-button type="warning" size="mini" @click="openDialogEdit('new',scope.row)">
						新建子节点
					</el-button>
					<el-button type="primary" size="mini" @click="openDialogEdit('edit',scope.row)">
						修改
					</el-button>
					<template v-if="scope.row.isDel==='0'">
						<el-tooltip content="置为无效" placement="bottom" effect="light" :enterable="false">
							<el-button type="danger" size="mini" circle icon="el-icon-delete"
								@click="invalidItemCategoryFn(scope.row)">
							</el-button>
						</el-tooltip>
					</template>
					<template v-else>
						<el-tooltip content="置为有效" placement="bottom" effect="light" :enterable="false">
							<el-button type="success" size="mini" circle icon="el-icon-upload"
								@click="invalidItemCategoryFn(scope.row)">
							</el-button>
						</el-tooltip>
					</template>
					
					<el-button type="warning" size="mini" v-if="scope.row.categoryLevel===1"
						@click="openDialogSort(scope.row)">
						设置显示目录
					</el-button>
					<el-button type="text" size="mini"
						@click="refreshRow(scope.row.id)" icon="el-icon-refresh">
					</el-button>
				</template>
			</el-table-column>
		</el-table>
		<!-- 增改查 -->
		<el-dialog :title="titleObj[pageType]" :visible.sync="dialogVisible" width="580px">
			<el-form ref="form" :model="form" label-width="110px" :rules="rules" label-suffix=":">
				<el-form-item label="父级目录名称" prop="" v-if="pageType==='new'">
					{{parentName}}
				</el-form-item>
				<el-form-item label="商品目录名称" prop="categoryName">
					<el-input v-model="form.categoryName"></el-input>
				</el-form-item>
				<el-form-item label="商品目录类型" prop="itemType">
					<el-select v-model="form.itemType">
						<el-option v-for="item in itemTypeList" :value="item.value" :label="item.label">{{ item.label }}</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="电商编码" prop="">
					<el-input v-model="form.dcCode"></el-input>
				</el-form-item>
				<el-form-item label="主要图片上传" prop="imgUrl" v-if="showPic == 1">
					<el-input style="display:none" v-model="form.imgUrl"></el-input>
					<el-upload :class="{'limited':showFlag||(mainFileList&&mainFileList.length>=1)}"
						list-type="picture-card" :action="fileUrl" :data="{ fileType: 14 }" :on-preview="handlePreview"
						:on-remove="mainHandleRemove" :before-remove="beforeRemove"
						:on-success="mainHandleAvatarSuccess" :on-error="handleAvatarError"
						:before-upload="beforeAvatarUpload" :headers="fileHeaders" :limit="1" :on-exceed="handleExceed1"
						:file-list="mainFileList" :disabled="showFlag">
						<i class="el-icon-plus"></i>
						<div slot="tip" class="el-upload__tip">
							<p>
								请上传1个图片，图片格式要求jpg/png格式，且不超过500kb
							</p>
						</div>
					</el-upload>
				</el-form-item>
				<el-form-item label="排序" prop="">
					<el-input v-model="form.sorts"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="save()">保 存</el-button>
			</span>
		</el-dialog>
		<!-- 设置导航中显示的目录 -->
		<el-dialog title="设置导航中显示的目录" :visible.sync="dialogVisibleSort" width="580px">
			<el-form ref="sortForm" :model="sortForm" label-width="110px" :rules="rules" label-suffix=":">
				<el-form-item label="类型" prop="itemType">
					<el-radio v-model="sortForm.itemType" label="0">办公用品</el-radio>
					<el-radio v-model="sortForm.itemType" label="1">工业用品</el-radio>
					<el-radio v-model="sortForm.itemType" label="3">集采协同</el-radio>
				</el-form-item>
				<el-form-item label="导航栏排序" prop="">
					<el-input v-model="sortForm.itemOrder"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisibleSort = false">取 消</el-button>
				<el-button type="primary" @click="saveSort()">保 存</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import {
		beforeUpload
	} from "@/util/common";
	// 上传文件
	import fileUpdata from "@/api/file.config";
	import moment from "moment";
	import {
		Base64
	} from "js-base64";
	import tools from "@/tools";
	import {
		deleteFile,
		removeByUrls,
		getFileUrl
	} from "@/api/common.api";
	import {
		queryGodCategoryZtreeAsyn,
		addItemCategory,
		editItemCategory,
		invalidItemCategory,
		updateOfficeSupplies,
		categoryInfo
	} from '@/api/admin.api'
	import {
		addCategory,
		editCategory,
		categoryPcList
	} from '@/api/admin.api'


	export default {
		name: 'catalogue-manager',
		data() {
			return {
				pageType: '',
				categoryType: this.$config.category.itemType,
				titleObj: {
					root: '新增根节点',
					new: '新增子节点',
					edit: '修改目录',
					root: '新增根节点',
				},
				tableData: [],
				dialogVisible: false,
				dialogVisibleSort: false,
				form: {
					categoryName: '',
					sorts: '',
					itemType: '自营',
					imgUrl: ''
				},

				env: process.env.NODE_ENV === 'development' ? 'dev' : 'pro',
				// 上传一般图片数据
				fileList: [],
				// 上传主要图片数据
				mainFileList: [],
				fileUrl: "",
				showFlag: false,
				fileHeaders: {},

				parentName: '',
				sortForm: {
					itemOrder: '',
					itemType: ''
				},
				rules: {
					categoryName: [{
						required: true,
						trigger: 'blur',
						message: '请输入商品目录名称'
					}],
					itemType: [{
						required: true,
						trigger: 'change',
						message: '请选择类型'
					}],
					imgUrl: [{
						required: false,
						trigger: 'change',
						message: '请选择分类图片'
					}],
				},
				showPic: 0,
				itemTypeList: [
					{value: "1", label: "自营"},
					{value: "2", label: "撮合"},
					{value: "3", label: "集采协同"}
				],
				queryParams: {
					isDel: ""
				}
			}
		},
		computed: {
			// 表格高度
			maxHeightNow() {
				const height = window.innerHeight
				return height - 270
			}
		},
		mounted() {

			this.fileHeaders = {
				...fileUpdata.headers()
			};
			this.fileUrl = fileUpdata.url;
			this.getTree()

			// categoryList().then((res)=>{
			//  console.log(res)
			// })
		},
		methods: {
			/**
			 * @description 上传的图片格式和大小
			 * @author 穆宏宇
			 * @date 2020-09-14 11:22:21
			 * @param
			 * @return
			 * */
			beforeAvatarUpload(file) {
				const typeList = ["png", "jpg"];
				const isJPG = beforeUpload(file, typeList);
				const isLt5kb = file.size / 1024 < 500;
				if (!isJPG) {
					this.$message.error("上传文件格式不符合!");
				}
				if (!isLt5kb) {
					this.$message.error("上传图片大小不能超过 500kb!");
				}
				return isJPG && isLt5kb;
			},
			// 上传错误文件时提示
			handleAvatarError(res, file) {
				this.$message.error("文件上传失败，请重试");
			},
			mainHandleAvatarSuccess(res, file) {

				if (this.env == 'dev') {
					this.form.imgUrl = "https://agshop.delinzl.cn/" + res.data.url;
				} else {
					this.form.imgUrl = res.data.url;
				}
				const curFile = {
					name: res.data.submittedFileName,
					url: this.form.imgUrl,
					id: res.data.id,
					fileType: res.data.fileType,
				};
				this.mainFileList.push(curFile);
				const ids = [];
				this.mainFileList.map((item) => {
					ids.push(item.id);
				});
			},
			/**
			 * @functionName submitUploadEditor
			 * @desccription 富文本批量上传图片
			 * @author 穆宏宇
			 * @date 2021-04-09 10:21:23
			 * @version v1.0.0
			 */
			submitUploadEditor() {
				if (this.fileDataEditor.length === 0) {
					this.$message({
						message: "请选择一般图片",
						type: 'warning'
					});
					return
				}
				if (this.goodsDescFileList.length + this.fileDataEditor.length > 10) {
					this.$message.warning(
						`最多可上传10张图片，您已超限`
					)
					return
				}
				const formData = new FormData(); // new formData对象
				this.$refs.upload.submit(); // 提交调用uploadFile函数
				formData.append('Authorization', tools.localRead('access_token')); // 添加token
				this.fileDataEditor.forEach(item => {
					formData.append("fileList", item.raw);
				})

				formData.append("fileType", 14);
				uploadMultipleFiles(formData).then(res => {
					this.$message({
						message: "上传成功",
						type: 'success'
					});
					res.forEach(item => {
						const {
							submittedFileName,
							id,
							url,
							fileType
						} = item
						// 获取光标所在位置
						let length = this.quill.getSelection().index;
						// 插入图片 res.url为服务器返回的图片地址
						this.quill.insertEmbed(length, "image", url);
						// 调整光标到最后
						this.quill.setSelection(length + 1);
						// this.goodsDescFileList.push({name: submittedFileName, id, url, fileType})
					})
					this.goodsDescFileList = [];
					this.fileDataEditor = []
				})
			},
			submitUpload() {
				if (this.fileData.length === 0) {
					this.$message({
						message: "请选择一般图片",
						type: 'warning'
					});
					return
				}
				if (this.fileList.length + this.fileData.length > 10) {
					this.$message.warning(
						`最多可上传10张图片，您已超限`
					)
					return
				}
				const formData = new FormData(); // new formData对象
				this.$refs.upload.submit(); // 提交调用uploadFile函数
				formData.append('Authorization', tools.localRead('access_token')); // 添加token
				this.fileData.forEach(item => {
					formData.append("fileList", item.raw);
				})

				formData.append("fileType", 14);
				uploadMultipleFiles(formData).then(res => {
					this.$message({
						message: "上传成功",
						type: 'success'
					});
					res.forEach(item => {
						const {
							submittedFileName,
							id,
							url,
							fileType
						} = item
						this.fileList.push({
							name: submittedFileName,
							id,
							url,
							fileType
						})
					})
					this.fileData = []
				})
			},
			// 上传文件
			uploadFile(file, fileList) {
				// console.log({file,fileList});
				// this.fileData.push(file.file);  // append增加数据
			},
			//监控上传文件列表
			handleChange(file, fileList) {
				this.fileData.push(file)
			},
			handleAvatarSuccess(res, file, fileList) {
				console.log(fileList)
				const {
					submittedFileName,
					id,
					url,
					fileType
				} = res.data;
				this.fileList.push({
					name: submittedFileName,
					id,
					url,
					fileType
				})
				const ids = [];
				this.fileList.map((item) => {
					ids.push(item.id);
				});
				this.formData.attachmentId = ids.toString();
			},
			// 预览附件
			handlePreview(file) {
				console.log('预览', file);
				if (file.response && file.response.data) {
					const {
						fileType,
						id
					} = file.response.data
					file['fileType'] = fileType
					file['id'] = id
				}
				getFileUrl(file.fileType, file.id).then(res => {
					this.dialogImageUrl = res
					this.dialogVisible = true
				})
			},
			// 取消上传图片
			mainHandleRemove(file, fileList) {
				if (file && file.status === "success") {
					const data = {
						urls: [file.url],
					};
					removeByUrls(data).then((res) => {
						const index = this.mainFileList.findIndex(item => item.url === file.url);
						this.mainFileList.splice(index, 1);
						this.form.imgUrl = '';
					});
				}
			},
			handleRemove(file, fileList) {
				const index = this.fileList.findIndex(item => item.uid === file.uid);
				if (index > -1) {
					this.fileList.splice(index, 1);
				}
				const dataIndex = this.fileData.findIndex(item => item.uid === file.uid);
				if (dataIndex > -1) {
					this.fileData.splice(dataIndex, 1);
				}
			},
			editorHandleRemove(file, fileList) {
				// console.log({file, fileList})
				// this.fileDataEditor = this.fileDataEditor.filter(item=>item.uid != )
				// this.goodsDescFileList = this.goodsDescFileList.filter(item=>item.url !== file.url)
			},
			// 选中上传图片限制
			handleExceed1(files, fileList) {
				this.$message.warning(
					`最多可上传1张图片，您已超限`
				)
			},
			handleExceed10(files, fileList) {
				this.$message.warning(
					`最多可上传10张图片，您已超限`
				)
			},

			// 移除上传图片
			beforeRemove(file, fileList) {
				if (file && file.status === "success") {
					return this.$confirm(`确定移除 ${file.name}？`);
				}

			},
			getTree() {
				categoryPcList('', '', this.queryParams.isDel).then(res => {
					this.tableData = res.rows
				})
			},
			load(tree, treeNode, resolve) {
				const parentCategoryId = tree.id
				categoryPcList(parentCategoryId, '', this.queryParams.isDel).then(res => {
					resolve(res.rows)
				}).catch(err => {
					console.log(err);
					resolve([])
				})
			},
			refreshRow(id) {
				var that = this;
				categoryPcList(id, '', this.queryParams.isDel).then(res => {
					if (res && res.rows.length) {
						that.$set(that.$refs.table.store.states.lazyTreeNodeMap, id, res.rows)
					}
				})
			},
			openDialogEdit(type, row) {
				this.pageType = type
				const {
					categoryName,
					sorts,
					id,
					parentCategoryId,
					categoryLevel,
					imgUrl
				} = row
				this.mainFileList = [];
				switch (type) {
					case 'root':
						this.form = {
							v: '1',
							categoryLevel: '1',
							itemType: row.itemType
						}
						this.dialogVisible = true
						this.showPic = 1;
						break;
					case 'new':
						this.parentName = categoryName
						this.form = {
							parentCategoryId: id,
							v: '1',
							categoryLevel: categoryLevel ? categoryLevel + 1 : 1,
							itemType: row.itemType,
							imgUrl: ''
						}
						this.dialogVisible = true
						if (row.categoryLevel == 2) {
							this.showPic = 1;
						} else {
							this.showPic = 0;
						}
						break;
					case 'edit':
						// this.form = {
						// 	categoryName,
						// 	sorts,
						// 	id,
						// 	parentCategoryId,
						// 	categoryLevel,
						// 	itemType: row.itemType,
						// 	imgUrl: row.imgUrl
						// }
						categoryInfo(id).then(res => {
							this.form = res
							this.dialogVisible = true
						})
						
						if (row.categoryLevel == 3 || row.categoryLevel == 1) {
							this.showPic = 1;
						} else {
							this.showPic = 0;
						}
						break;
					default:
						break;
				}
				if (row.imgUrl) {
					if (this.showPic == 1) {
						this.mainFileList = [{
							name: '',
							url: this.form.imgUrl,
							id: '',
							fileType: 14,
						}];
					}
				}

			},
			save(row) {
				var that = this;
				let pid = that.form.parentCategoryId || ''
				that.$refs.form.validate((valid) => {
					if (valid) {
						switch (that.pageType) {
							case 'root':
							case 'new':
								// addItemCategory(this.form).then(res=>{
								addCategory(that.form).then(res => {
									that.$alert('保存成功', '提示', {
										confirmButtonText: '确定',
										type: 'success',
										callback: action => {
											that.parentName = ''
											that.refreshRow(pid)
											that.dialogVisible = false;
										}
									})
								}).catch(err => {
									this.$message.error(err.msg)
								})
								break;
							case 'edit':
								// editItemCategory(this.form).then(res=>{
								editCategory(that.form).then(res => {
									that.$alert('保存成功', '提示', {
										confirmButtonText: '确定',
										type: 'success',
										callback: action => {
											if (pid) {
												that.refreshRow(pid)
											} else {
												that.getTree()
											}
											that.dialogVisible = false;
										}
									})
								}).catch(err => {
									this.$message.error(err.msg)
								})
								break;

							default:
								break;
						}
					}
				})
			},
			// 设置有效性
			invalidItemCategoryFn(row) {
				const data = {
					id: row.id,
					isDel: row.isDel === '1' ? '0' : '1'
				}
				const pid = this.form.parentCategoryId || ''
				this.$alert(`确定置为${row.v==='1'?'无效':'有效'}吗？`, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'success',
					callback: action => {
						if (action === 'confirm') {
							invalidItemCategory(data).then(res => {
								this.$alert('保存成功', '提示', {
									confirmButtonText: '确定',
									type: 'success',
									callback: action => {
										row.isDel = data.isDel
										if (pid) {
											this.refreshRow(pid)
										} else {
											this.getTree()
										}
									}
								})
							})
						}
					}
				})
			},
			// 以下fn 第二个弹窗相关
			openDialogSort(row) {
				this.sortForm.categoryId = row.id
				this.sortForm.itemType = row.itemType
				this.sortForm.itemOrder = row.itemOrder
				this.dialogVisibleSort = true
			},
			saveSort() {
				this.$refs.sortForm.validate((valid) => {
					if (valid) {
						let data = {
							// NavUpdateDtoNavUpdateDto: {
							categoryId: this.sortForm.categoryId,
							itemOrder: this.sortForm.itemOrder,
							itemType: this.sortForm.itemType,
							// }
						}
						updateOfficeSupplies(data).then(res => {
							this.$alert('保存成功', '提示', {
								confirmButtonText: '确定',
								type: 'success',
								callback: action => {
									this.getTree()
									this.dialogVisibleSort = false
								}
							})
						})
					}
				})
			}
		}
	}
</script>

<style lang='scss' scoped>
	.catalogue-manager {

		th,
		td,
		tr {
			text-align: left !important;
			padding-left: 40px;
			padding-right: 40px;
		}

		.mb10 {
			margin-bottom: 10px;
		}
	}
	
	.success{
		color: #F56C6C;
	}
</style>
